/**
 * 
 */
package com.game.codec;


import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.game.request.BaseRequest;
import com.game.request.RequestFactory;



/**
 * @author lushouzhi
 *
 */
public class RequestDecoder extends CumulativeProtocolDecoder {
	
	  protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
	    // remember the start position
	    int start = in.position();
	    if (in.remaining() > 2) {
	      short length = in.getShort();
	      if (length < 0) {
	        in.position(start);
	        return false;
	      } else if (in.remaining() < length - 2) {
	        in.position(start);
	        return false;
	      }
	      byte gameType=in.get();
	      byte cmdId=in.get();
	      int readPos = 4;
	      BaseRequest req = RequestFactory.create(gameType,cmdId);
	      if(req==null){
	    	  return false;
	      }
	      if(length-readPos<=in.remaining()){
	    	  req.setBody(in);
	    	  req.setIoSession(session);
	      }else{
	    	  return false;
	      }
	      out.write(req);
	      return true;
	    } else {
	      return false;
	    }
	  }
}
